package org.example.web.controller;

import com.google.common.cache.Cache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.common.aspect.SysLog;
import org.example.common.enums.AppGlobalKey;
import org.example.model.UserDO;
import org.example.model.base.SuperEntity;
import org.example.services.UserService;
import org.example.web.resp.R;
import org.example.web.req.RegisterREQ;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.example.common.enums.ResultEnum.ExistResult;
import static org.example.common.enums.ResultEnum.ParamErrResult;

@Api(tags = "用户")
@RestController
@RequestMapping("user")
public class AppUserRegisterController {

    @Autowired
    private UserService userService;

    @Autowired
    @Qualifier("guavaCache")
    private Cache<String, Object> guavaCaCHe;

    @SysLog(operation = "获取手机验证码")
    @ApiOperation("获取手机验证码")
    @RequestMapping(value = "getPhoneCode",method = RequestMethod.GET)
    public R getPhoneCode(@RequestParam("phone") String phone){

        if(StringUtils.isEmpty(phone)){
            return R.error(ParamErrResult.getCode(),"手机号不能为空！");
        }
        String regex="^1[3456789]\\d{9}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(phone);
        boolean isMatch = m.matches();
        if(!isMatch){
            return R.error(ParamErrResult.getCode(),"手机号格式错误！");
        }

        guavaCaCHe.put(AppGlobalKey.APP_USER_PHONE+phone,"123456");
        return R.ok(123456);
    }

    @SysLog(operation = "用户手机注册")
    @ApiOperation(value = "用户手机注册",notes = "注册完成后，跳转到登录")
    @RequestMapping(value = "register",method = RequestMethod.POST)
    public R register(@RequestBody @Validated(SuperEntity.Save.class) RegisterREQ appUserDO){

        UserDO old = userService.getOneByPhone(appUserDO.getMobile());
        if(old!=null){
            return R.error(ExistResult.getCode(),"手机号码已注册");
        }

        UserDO old2 = userService.getOneByUsername(appUserDO.getUsername());
        if(old2!=null){
            return R.error(ExistResult.getCode(),"用户名已被使用");
        }

        String code = (String)guavaCaCHe.getIfPresent(AppGlobalKey.APP_USER_PHONE + appUserDO.getMobile());
        if(!code.equals(appUserDO.getCode())){
            return R.error(ParamErrResult.getCode(),"验证码错误");
        }
        guavaCaCHe.invalidate(AppGlobalKey.APP_USER_PHONE + appUserDO.getMobile());
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(appUserDO,userDO);
        userService.save(userDO);
        return R.ok(appUserDO);
    }
}
